import { BanList } from "./BanList";
import { Config } from "./utils/config";
import { urlAccessible } from "./utils/urlAccessible";

class Background {
  banList: BanList;
  config: Config;
  static instance: null | Background = null;

  private constructor() {
    this.banList = new BanList();
    this.config = new Config();
    this.banList.init();
    this.banList.updateList();
    this.registerContentScript();
    this.listenNavigation();
  }

  static getInstance() {
    if (Background.instance === null) {
      Background.instance = new Background();
    }
    return Background.instance;
  }

  private listenNavigation() {
    chrome.webNavigation.onCommitted.addListener((details) => {
      const ban = !urlAccessible(this.banList.getList(), details.url);
      if (
        details.url.startsWith("http") &&
        details.transitionType === "link" &&
        details.frameType === "outermost_frame" &&
        details.documentLifecycle === "active" &&
        ban &&
        this.config.getRedirect()
      ) {
        chrome.tabs.remove(details.tabId);
        chrome.notifications.create({
          type: "basic",
          iconUrl: "icon.png",
          title: "block redirect",
          message: "blocking: " + details.url,
        });
      }
    });
  }
  async registerContentScript() {
    const props = {
      matches: ["*://*/*"],
      excludeMatches: [],
      allFrames: true,
      matchOriginAsFallback: true,
    };

    await chrome.scripting.registerContentScripts([
      {
        id: "inject_main",
        js: ["inject_main.js"],
        world: "MAIN",
        runAt: "document_start",
        ...props,
      },
      {
        id: "inject_isolated",
        js: ["inject_isolated.js"],
        runAt: "document_start",
        ...props,
      },
    ]);
  }
}

const activate = () => {
  Background.getInstance();
};

// chrome.runtime.onStartup.addListener(activate);
chrome.runtime.onInstalled.addListener(activate);
